package cn.lijiancn01.demo.business.menu.service;

import cn.lijiancn01.demo.business.menu.biz.MenuBiz;
import cn.lijiancn01.demo.business.menu.model.MenuBO;
import cn.lijiancn01.demo.business.menu.model.MenuDO;
import cn.lijiancn01.demo.business.menu.model.MenuRoot;
import cn.lijiancn01.demo.business.menu.model.MenuSchemaBO;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MenuService {
    @Autowired
    private MenuBiz menuBiz;

    public MenuRoot list() {
        MenuRoot root = new MenuRoot();
        MenuBO group1 = new MenuBO();
        MenuBO group2 = new MenuBO();
        root.setPages(Lists.newArrayList(group1, group2));
        //group1
        group1.setLabel("Home");
        group1.setUrl("/");
        group1.setSchema(new MenuSchemaBO("page", "Home", "首页"));
        //group2
        List<MenuDO> menus = menuBiz.list();
        Map<String, List<MenuDO>> pidMap = menus.stream().collect(Collectors.groupingBy(MenuDO::getPid));
        //一级菜单
        List<MenuDO> firstLevelMenus = menus.stream()
                .filter(t -> StringUtils.isBlank(t.getPid()) || "0".equals(t.getPid()))
                .filter(t -> StringUtils.containsAny(t.getLabel(), "基础资料", "系统管理"))
                .collect(Collectors.toList());
        group2.setChildren(build(firstLevelMenus, pidMap));
        return root;
    }

    /**
     * 递归返回菜单树
     *
     * @param menus
     * @param pidMap
     * @return
     */
    private List<MenuBO> build(List<MenuDO> menus, Map<String, List<MenuDO>> pidMap) {
        List<MenuBO> results = new ArrayList<>();
        for (MenuDO menu : menus) {
            MenuBO menuBO = new MenuBO();
            results.add(menuBO);

            menuBO.setLabel(menu.getLabel());
            //判断是否有子节点
            if (pidMap.containsKey(menu.getId())) {//有，则是目录
                menuBO.setUrl(menu.getId());
                //递归
                menuBO.setChildren(build(pidMap.get(menu.getId()), pidMap));
            } else {//没有，则是叶子节点
                //方式一：直接写页面内容
                /*MenuSchemaBO menuSchemaBO = new MenuSchemaBO();
                menuSchemaBO.setTitle(menu.getLabel());
                menuSchemaBO.setType("page");
                menuSchemaBO.setBody(menu.getLabel() + " 页面内容...");
                menuBO.setSchema(menuSchemaBO);*/
                //方式二：引用 json 配置页面
                menuBO.setSchemaApi(String.format("get:/pages/%s/%s.json", menu.getId(), menu.getId()));
            }
        }
        return results;
    }
}
